﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Reflection;
using System.Data;
using System.Collections;
using Infragistics.Win.UltraWinGrid;
using System.Globalization;
using Crystal.CustomControls;
using Infragistics.Documents.Excel;
using Infragistics.Win;
using System.Drawing;

namespace Crystal.CLL
{
    public static class CommonCLL
    {
        #region Fields
        public static Int16 UserID;
        public static int mintNewOptionID = 0;
        public static string UserName;
        public static string UserFullName;
        public static int m_strSelectIDValue = -1;
        public static string m_strSelectTextValue = "---Select---";
        public static Int16 m_strNewIDValue = -3;
        public static string m_strNewTextValue = "---New---";
        public static string mstrMsgBoxCaption = "CRYSTAL";
        public static int mintInvestorDefaultSearchPercentage = 75;
        public static int mintMinSearchLength = 10;
        public static string mstrConnectionstring = string.Empty; //'= "Persist Security Info=False;database=Crystal_DBMGT;server=Sanghvi-PC;user id=sa;password=sa010#;Current Language=English;";
        public static string mstrContextConnectionstring = string.Empty; 
        public static string[] supportedFormats = new string[] {
	"dd-MM-yyyy",
	"dd-MM-yy",
	"dd-MM-yy HH:mm:ss tt",
	"dd-MM-yyyy HH:mm:ss tt",
	"dd-MMM-yy",
	"dd-MMM-yyyy HH:mm:ss tt",
	"dd-MMM-yy HH:mm:ss tt",
	"dd/MM/yyyy",
	"dd/MM/yy",
	"dd/MM/yy HH:mm:ss tt",
	"dd/MM/yyyy HH:mm:ss tt",
	"dd/MMM/yy",
	"dd/MMM/yyyy HH:mm:ss tt",
	"dd/MMM/yy HH:mm:ss tt",
	"MM-dd-yyyy",
	"MM-dd-yy",
	"MM-dd-yy HH:mm:ss tt",
	"MM-dd-yyyy HH:mm:ss tt",
	"MMM-dd-yy",
	"MMM-dd-yyyy HH:mm:ss tt",
	"M-dd-yyyy HH:mm:ss tt",
	"mm-dd-yyyy HH:mm:ss tt",
	"MMM-dd-yy HH:mm:ss tt",
	"MM/dd/yyyy",
	"MM/dd/yy",
	"MM/dd/yy HH:mm:ss tt",
	"MM/dd/yyyy HH:mm:ss tt",
	"MMM/dd/yy",
	"MMM/dd/yyyy HH:mm:ss tt",
	"MMM/dd/yy HH:mm:ss tt",
	"d/MM/yyyy HH:mm:ss tt",
	"MM/d/yyyy HH:mm:ss tt",
	"M/dd/yyyy HH:mm:ss tt",
	"dd/M/yyyy HH:mm:ss tt",
	"d/MM/yyyy",
	"MM/d/yyyy",
	"M/dd/yyyy",
	"dd/M/yyyy",
	"d-MM-yyyy HH:mm:ss tt",
	"MM-d-yyyy HH:mm:ss tt",
	"M-dd-yyyy HH:mm:ss tt",
	"dd-M-yyyy HH:mm:ss tt",
	"d-MM-yyyy",
	"MM-d-yyyy",
	"M-dd-yyyy",
	"dd-M-yyyy",
	"d/M/yyyy HH:mm:ss tt",
	"M/d/yyyy HH:mm:ss tt",
	"d/M/yyyy",
	"M/d/yyyy",
	"d-M-yyyy HH:mm:ss tt",
	"M-d-yyyy HH:mm:ss tt",
	"d-M-yyyy",
	"M-d-yyyy"
};
        
        #endregion

        #region "Enumerator"
        public enum MessageBoxIcons
        {
            Information = 1,
            Warning = 2,
            Error = 3
        }
        #endregion

        #region Methods

        #region DB Methods

        #endregion

        /// <summary>
        /// Genrates Xml from datatable
        /// </summary>
        /// <param name="pdtData"></param>
        /// <returns></returns>
        /// <remarks></remarks>

        public static string GetXMlFromDataTable(DataTable pdtData, string[] larrExcludingCols)
        {
            System.Text.StringBuilder lstrData = new System.Text.StringBuilder();
            string Value = "";
            int RowCount = 1;
            int GridRowsCount = pdtData.Rows.Count;
            try
            {
                lstrData.Append("<ROOT>");
                foreach (DataRow lrowInvestor in pdtData.Rows)
                {
                    lstrData.Append("<Row ");
                    foreach (DataColumn lcolInvestor in pdtData.Columns)
                    {
                        if (larrExcludingCols.Contains(lcolInvestor.ColumnName) == false)
                        {
                            lstrData.Append(lcolInvestor.ColumnName.Replace(" ", ""));
                            lstrData.Append("=\"");
                            if ((string.IsNullOrEmpty(lrowInvestor[lcolInvestor.ColumnName].ToString())))
                            {
                                Value = " ";
                            }
                            else
                            {
                                Value = lrowInvestor[lcolInvestor.ColumnName].ToString().Trim();
                            }
                            lstrData.Append(ReplaceSpecialChar(Value));
                            lstrData.Append("\" ");
                        }
                    }
                    lstrData.Append("/>");
                    lstrData.Append(Environment.NewLine);
                    RowCount = RowCount + 1;
                }
                lstrData.Append("</ROOT>");
                return lstrData.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                lstrData = null;
                pdtData = null;
            }
        }

        private static string ReplaceSpecialChar(string val)
        {
            return val.Trim().Replace("&", "&amp;").Replace("'", "&apos;").Replace("<", "&lt;").Replace(">", "&gt;");
        }

        public static string GetXMlFromUltraGrid(CrystalUltraGrid grdData, string[] larrExcludingCols, string[] larrKeyCols,bool pblnAllRows)
        {
            System.Text.StringBuilder lstrData = new System.Text.StringBuilder();
            string Value = "";
            int RowCount = 1;

            int GridRowsCount = grdData.Rows.Count;
            try
            {
                lstrData.Append("<ROOT>");
                foreach (UltraGridRow lrowInvestor in grdData.Rows)
                {
                    if (lrowInvestor.Hidden == true || (pblnAllRows==false && lrowInvestor.Selected==false))
                    {
                        continue;
                    }
                    lstrData.Append("<Row ");
                    foreach (UltraGridColumn lcolInvestor in grdData.Rows.Band.Columns)
                    {
                        if (larrExcludingCols.Contains(lcolInvestor.Header.Caption) == false)
                        {
                            lstrData.Append(lcolInvestor.Header.Caption.Replace(" ", ""));
                            lstrData.Append("=\"");
                            if (larrKeyCols.Contains(lcolInvestor.Header.Caption))
                            {
                                if ((string.IsNullOrEmpty(lrowInvestor.Cells[lcolInvestor.Header.Caption].Value.ToString())))
                                {
                                    Value = "0";
                                }
                                else
                                {
                                    Value = lrowInvestor.Cells[lcolInvestor.Header.Caption].Tag.ToString().Trim();
                                }
                            }
                            else
                            {
                                if ((string.IsNullOrEmpty(lrowInvestor.Cells[lcolInvestor.Header.Caption].Value.ToString())))
                                {
                                    Value = " ";
                                }
                                else
                                {
                                    Value = lrowInvestor.Cells[lcolInvestor.Header.Caption].Value.ToString().Trim();
                                }
                            }
                            lstrData.Append(ReplaceSpecialChar(Value));
                            lstrData.Append("\" ");
                        }
                    }
                    lstrData.Append("/>");
                    lstrData.Append(Environment.NewLine);
                    RowCount = RowCount + 1;
                }
                lstrData.Append("</ROOT>");
                return lstrData.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                lstrData = null;
                //pdtData = null;
            }
        }

        /// <summary>
        /// To replace the string to consider accented characters alongwith the regular characters
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static string ReplaceForAccentedChars(string str)
        {

            //àäáâãÀÄÁÂÃèéëêËÈÉÊîíìïÍÎÏÌòóôõöÕÖÒÓÔùúûüÚÙÛÜýÿÝŸñÑ
            string strA = "aàäáâãÀÄÁÂÃ";
            string strE = "eèéëêËÈÉÊ";
            string strI = "iîíìïÍÎÏÌ";
            string strO = "oòóôõöÕÖÒÓÔ";
            string strU = "uùúûüÚÙÛÜ";
            string strY = "yýÿÝŸ";
            string strN = "nñÑ";
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if (strA.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strA + "]");
                }
                else if (strE.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strE + "]");
                }
                else if (strI.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strI + "]");
                }
                else if (strO.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strO + "]");
                }
                else if (strU.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strU + "]");
                }
                else if (strY.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strY + "]");
                }
                else if (strN.Contains(c.ToString(), StringComparison.CurrentCultureIgnoreCase))
                {
                    sb.Append("[" + strN + "]");
                }
                else
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static string RemoveDiacritics(string text)
        {
            return string.Concat(
                text.Normalize(NormalizationForm.FormD)
                .Where(ch => CharUnicodeInfo.GetUnicodeCategory(ch) !=
                                              UnicodeCategory.NonSpacingMark)
              ).Normalize(NormalizationForm.FormC);
        }

        public static bool FocusOnExistingInstanceByName(string Filename)
        {
            try
            {
                for (int i = 0; i <= Application.OpenForms.Count - 1; i++)
                {
                    switch (Filename)
                    {
                        case "ListUsers":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "AddEditUser":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "frmUploadInvestor":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;

                        case "frmInvestorManagement":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "FundManagement":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "UploadeSource":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "frmClientManagement":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "frmProjectManagement":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "MergersAndAcquisitions":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "frmAddModifyInvestor":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "DataHub":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                        case "Review":
                            if ((Application.OpenForms[i].Name == Filename))
                            {
                                return false;
                            }
                            break;
                    }
                }
                return true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return false;
            }
        }

        public static bool FocusOnExistingInstanceByText(string Filename)
        {
            try
            {
                for (int i = 0; i <= Application.OpenForms.Count - 1; i++)
                {

                    if ((Application.OpenForms[i].Text == Filename))
                    {
                        Application.OpenForms[i].Focus();
                        return false;
                    }

                }
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        /// <summary>
        /// To check if text box is empty.
        /// </summary>
        /// <param name="strText"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool IsEmpty(string strText)
        {
            if (string.IsNullOrEmpty(strText.Trim()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// checks the dataset is Empty 
        /// </summary>
        /// <param name="ds"></param>
        /// <returns></returns>
        /// <remarks></remarks>

        public static bool CheckEmptyDataSet(DataSet ds)
        {

            if (ds == null)
                return true;
            if (object.ReferenceEquals(ds, DBNull.Value))
                return true;
            if (ds.Tables.Count == 0)
                return true;
            return false;
        }

        /// <summary>
        /// checks the datatable is Empty 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool CheckEmptyDataTable(DataTable dt)
        {
            if (dt == null)
                return true;
            if (object.ReferenceEquals(dt, DBNull.Value))
                return true;
            if (dt.Rows.Count == 0)
                return true;
            return false;
        }

        /// <summary>
        /// checks the datatable 
        /// </summary>
        /// <param name="dt"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool CheckNothingDataTable(DataTable dt)
        {
            if (dt == null)
                return true;
            if (object.ReferenceEquals(dt, DBNull.Value))
                return true;
            return false;
        }

        /// <summary>
        /// Checks The Duplicate Columns
        /// </summary>
        /// <param name="dtInvestor"></param>
        /// <param name="selectSheet"></param>
        /// <param name="isColumDupliacte"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool CheckDuplicateColumn(ref string colName, string filename, DataTable dtInvestor, string selectSheet, ref bool isColumDupliacte)
        {
            //bool functionReturnValue = false;
            ArrayList ExcelColumn = new ArrayList();
            int CellCount = 0;
            int CurrentCount = 1;
            CellCount = dtInvestor.Columns.Count;
            CurrentCount = 1;

            while (CurrentCount < CellCount)
            {
                if (string.IsNullOrEmpty(dtInvestor.Columns[CurrentCount].ColumnName))
                    //break; // TODO: might not be correct. Was : Exit While
                    return true;
                if (ExcelColumn.IndexOf(dtInvestor.Columns[CurrentCount].ColumnName.ToUpper()) > 0)
                {
                    colName = dtInvestor.Columns[CurrentCount].ColumnName.Trim();
                    // MessageBox.Show("Column '" + ExcelRange.Text & "' is duplicate in file", mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                    ExcelColumn = null;
                    isColumDupliacte = true;
                    //ExcelWorkBook.Workbooks.Close()
                    //ExcelWorkBook.Quit()
                    return false;
                }
                ExcelColumn.Add(dtInvestor.Columns[CurrentCount].ColumnName.ToUpper());
                CurrentCount += 1;
            }
            return true;
        }

        /// <summary>
        /// Checks The Duplicate Columns
        /// </summary>
        /// <param name="dtInvestor"></param>
        /// <param name="selectSheet"></param>
        /// <param name="isColumDupliacte"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool CheckDuplicateColumn(ref string colName, Workbook internalWorkBook, string selectSheet, int minRowCount, int maxRowCount, int minCellCount, int maxCellCount)
        {
            //bool functionReturnValue = false;
            ArrayList ExcelColumn = new ArrayList();
            //int CellCount = 0;
            int CurrentCount = minCellCount;
            Worksheet lworksheet = internalWorkBook.Worksheets[selectSheet];
            Boolean lblnStatus = true;
            try
            {
                while (CurrentCount < maxCellCount)
                {
                    if (lworksheet.Rows[minRowCount].Cells[CurrentCount].Value != null)
                    {
                        if (ExcelColumn.IndexOf(lworksheet.Rows[minRowCount].Cells[CurrentCount].Value.ToString().ToUpper()) >= 0)
                        {
                            colName = colName + lworksheet.Rows[minRowCount].Cells[CurrentCount].Value.ToString().Trim() + ", ";
                            // MessageBox.Show("Column '" + ExcelRange.Text & "' is duplicate in file", mstrMsgBoxCaption, MessageBoxButtons.OK, MessageBoxIcon.Information)
                            //ExcelColumn = null;
                            //isColumDupliacte = true;
                            //ExcelWorkBook.Workbooks.Close()
                            //ExcelWorkBook.Quit()
                            lblnStatus = false;
                            //return false;
                            //CurrentCount += 1;
                        }
                    }
                    ExcelColumn.Add(lworksheet.Rows[minRowCount].Cells[CurrentCount].Value.ToString().ToUpper());
                    CurrentCount += 1;
                }
                if (lblnStatus == false)
                {
                    colName = colName.TrimEnd(' ');
                    colName = colName.TrimEnd(',');
                }
                //lblnStatus = true;
                
            }
            catch (Exception ex)
            {
                System.Text.StringBuilder MsgLog = new System.Text.StringBuilder();
                MsgLog.Append("There is error in CheckDuplicateColumn in CommonCLL");
                MsgLog.Append(Environment.NewLine);
                MsgLog.Append("Error Details:- ");
                MsgLog.Append(ex.ToString());
                MsgLog = null;
                return false;
            }

            return lblnStatus;
        }

        /// <summary>
        /// Checks The System Columns
        /// </summary>
        /// <param name="dtInvestor"></param>
        /// <param name="selectSheet"></param>
        /// <param name="isColumDupliacte"></param>
        /// <returns></returns>
        /// <remarks></remarks>
        public static bool CheckSystemColumns(ref string colName, Workbook internalWorkBook, string selectSheet, int minRowCount, int maxRowCount, int minCellCount, int maxCellCount, string[] parrSysCols)
        {
            ArrayList ExcelColumn = new ArrayList();
            int CurrentCount = minCellCount;
            WorksheetRow lworksheetrow = internalWorkBook.Worksheets[selectSheet].Rows[minRowCount];
            Boolean lblnStatus = true;

            while (CurrentCount < maxCellCount)
            {
                if (lworksheetrow.Cells[CurrentCount].Value != null)
                {
                    if (parrSysCols.Contains(lworksheetrow.Cells[CurrentCount].Value.ToString().ToUpper()))
                    {
                        colName = colName + lworksheetrow.Cells[CurrentCount].Value.ToString().Trim() + ", ";
                        lblnStatus = false;
                    }
                }
                CurrentCount += 1;
            }
            if (lblnStatus == false)
            {
                colName = colName.TrimEnd(' ');
                colName = colName.TrimEnd(',');
            }
            //lblnStatus = true;
            return lblnStatus;
        }

        public static bool Contains(this string source, string toCheck, StringComparison comp)
        {
            return source.IndexOf(toCheck, comp) >= 0;
        }
        public static  string  AddSeprator(string stringValue)
        {
            stringValue = stringValue.Replace(",", "");
            bool isbool = false;
            Int64 value = 0;
            isbool = Int64.TryParse(stringValue , out value);
            if (isbool)
            {
                stringValue = value.ToString("#,##0");
            }
            return stringValue;
        }
        /// <summary>
        /// To check/uncheck permissions from Permission Grid
        /// </summary>
        /// <remarks></remarks>
        /// 

        //public void CheckUncheckPermissions(ref UltraGrid ultraGridRow, ref bool IsChecked)
        //{
        //    try
        //    {
        //        if (CheckNothingUltraGridActiveCell(ultraGridRow) == false)
        //            return;
        //        if (ultraGridRow.ActiveCell == null)
        //            return;
        //        if (ultraGridRow.ActiveCell.Column.Header.Caption == "Category" || ultraGridRow.ActiveCell.Column.Header.Caption == "Category Permissions")
        //            return;
        //        bool IsAnyFalseChildrow = false;
        //        IsChecked = true;
        //        if (ultraGridRow.ActiveRow.HasChild == false)
        //        {
        //            if (ultraGridRow.ActiveRow.ParentRow != null)
        //            {
        //                if (ultraGridRow.ActiveRow.Cells(ultraGridRow.ActiveCell.Column.Header.Caption).Text == "True")
        //                {
        //                    ultraGridRow.ActiveRow.ParentRow.Cells(ultraGridRow.ActiveCell.Column.Header.Caption).Value = "False";
        //                }
        //                else
        //                {
        //                    foreach (UltraGridRow dr in ultraGridRow.ActiveRow.ParentRow.ChildBands.Item(0).Rows)
        //                    {
        //                        if (dr.Index != ultraGridRow.ActiveRow.Index)
        //                        {
        //                            if (dr.Cells(ultraGridRow.ActiveCell.Column.Header.Caption).Value == "False")
        //                            {
        //                                IsAnyFalseChildrow = true;
        //                            }
        //                        }
        //                    }
        //                    if (IsAnyFalseChildrow == false)
        //                    {
        //                        ultraGridRow.ActiveRow.ParentRow.Cells(ultraGridRow.ActiveCell.Column.Header.Caption).Value = "True";
        //                    }
        //                }
        //            }
        //        }
        //        if (ultraGridRow.ActiveCell.Column.Header.Caption == "Select")
        //        {
        //            if (ultraGridRow.ActiveRow.Cells("Select").Text == "True")
        //            {
        //                ultraGridRow.ActiveRow.Cells("Select").Value = "False";
        //                if (ultraGridRow.ActiveRow.HasChild)
        //                {
        //                    foreach (UltraGridRow dr in ultraGridRow.ActiveRow.ChildBands.Item(0).Rows)
        //                    {
        //                        dr.Cells("Select").Value = "False";
        //                    }
        //                }
        //            }
        //            else
        //            {
        //                ultraGridRow.ActiveRow.Cells("Select").Value = "True";
        //                if (ultraGridRow.ActiveRow.HasChild)
        //                {
        //                    foreach (UltraGridRow dr in ultraGridRow.ActiveRow.ChildBands.Item(0).Rows)
        //                    {
        //                        dr.Cells("Select").Value = "True";
        //                    }
        //                }
        //            }
        //        }
        //        ((DataSet)ultraGridRow.DataSource).AcceptChanges();
        //    }
        //    catch (Exception ex)
        //    {
        //        //'Logging
        //        System.Text.StringBuilder MsgLog = new System.Text.StringBuilder();
        //        MsgLog.Append("There is error in CheckUncheckPermissions in mdlCommon");
        //        MsgLog.Append(Environment.NewLine);
        //        MsgLog.Append("Error Details:- ");
        //        MsgLog.Append(ex.ToString());
        //        CreateErrorLog(MsgLog);
        //        MsgLog = null;

        //    }
        //}

        #region "Data Reader Read Only"
        public static void ChangeDataReaderDataSet(ref DataSet ChkTable)
        {
            foreach (DataTable dttable in ChkTable.Tables)
            {
                foreach (DataColumn lCol in dttable.Columns)
                {
                    lCol.ReadOnly = false;
                    lCol.AllowDBNull = true;
                }
            }
        }
        public static void ChangeDataReaderDataTable(ref DataTable ChkTable)
        {
            foreach (DataColumn lCol in ChkTable.Columns)
            {
                lCol.ReadOnly = false;
                lCol.AllowDBNull = true;
            }
        }
        #endregion

        #region Datatable
        public static bool DropDownAtFirst(ref DataTable dataTable, string idColumn, string valueColumn, int rowValue, string rowText)
        {
            if (dataTable == null)
                return true;
            DataRow drDataRow = null;
            drDataRow = dataTable.NewRow();
            drDataRow[idColumn] = rowValue;
            drDataRow[valueColumn] = rowText;
            dataTable.Rows.InsertAt(drDataRow, 0);
            return true;
        }

        /// <summary>
        /// Add a value in drop down at last place
        /// </summary>
        /// <param name="dataTable">Data Table to access</param>
        /// <param name="idColumn">ID Column of row</param>
        /// <param name="valueColumn">Text Column of row</param>
        /// <param name="rowValue">ID Value of row</param>
        /// <param name="rowText">Text Value of row</param>
        /// <remarks></remarks>
        public static bool AddRowInDropDownAtLast(ref DataTable dataTable, string idColumn, string valueColumn, int rowValue, string rowText)
        {
            try
            {
                if (CheckEmptyDataTable(dataTable))
                {
                    return false;
                }
                DataRow drDataRow = null;
                drDataRow = dataTable.NewRow();
                drDataRow[idColumn] = rowValue;
                drDataRow[valueColumn] = rowText;
                dataTable.Rows.Add(drDataRow);
                return true;
            }
            catch (Exception ex)
            {
                System.Text.StringBuilder MsgLog = new System.Text.StringBuilder();
                MsgLog.Append("There is error in AddRowInDropDownAtLast in mdlCommon");
                MsgLog.Append(Environment.NewLine);
                MsgLog.Append("Error Details:- ");
                MsgLog.Append(ex.ToString());
                MsgLog = null;
                return false;
            }
        }
        #endregion

        #region MessageBox
        /// <summary>
        /// To show a message in Message Box
        /// </summary>
        /// <param name="strMessage">Message to be shown</param>
        /// <remarks></remarks>
        public static void ShowMessage(string strMessage, MessageBoxIcons messageboxicon)
        {
            switch (messageboxicon)
            {
                case MessageBoxIcons.Information:
                    MessageBox.Show(strMessage, mstrMsgBoxCaption, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
                    break;
                case MessageBoxIcons.Warning:
                    MessageBox.Show(strMessage, mstrMsgBoxCaption, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Warning);
                    break;
                case MessageBoxIcons.Error:
                    MessageBox.Show(strMessage, mstrMsgBoxCaption, MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                    break;
            }
        }
        #endregion

        public static bool DropDownAtLast(ref DataTable dataTable, string idColumn, string valueColumn, int rowValue, string rowText)
        {
            if (dataTable == null)
                return true;
            DataRow drDataRow = null;
            drDataRow = dataTable.NewRow();
            drDataRow[idColumn] = rowValue;
            drDataRow[valueColumn] = rowText;
            dataTable.Rows.Add(drDataRow);
            return true;
        }

        public static bool AddAtFirstIndexInDropDown(ref DataTable dataTable, string idColumn, string valueColumn, int rowValue, string rowText)
        {
            if (dataTable == null)
                return true;
            DataRow drDataRow = null;
            drDataRow = dataTable.NewRow();
            drDataRow[idColumn] = rowValue;
            drDataRow[valueColumn] = rowText;
            dataTable.Rows.InsertAt(drDataRow, 0);
            return true;
        }

        public static bool blnRowBlank(DataRow lrowHistory)
        {
            bool Blank = false;
            for (int iCnt = 0; iCnt <= lrowHistory.Table.Columns.Count - 1; iCnt++)
            {
                if (!string.IsNullOrEmpty(lrowHistory[iCnt].ToString()))
                {
                    Blank = false;
                    break; // TODO: might not be correct. Was : Exit For
                }
                else
                {
                    Blank = true;
                }
            }
            return Blank;
        }

        /// <summary>
        /// Check the status if there are any changes in the grid
        /// </summary>
        /// <param name="pblnAnyDataChange">To set the status</param>
        /// <param name="grdData">The grid to check in</param>
        public static void CheckUpdateStatus(ref bool pblnAnyDataChange,CrystalUltraGrid grdData)
        {
            if (grdData.ActiveRow != null)
            {
                if (grdData.ActiveRow.DataChanged && pblnAnyDataChange == false)
                {
                    pblnAnyDataChange = true;
                }
            }
        }

        public static bool IsNullToTrueForBool(object i)
        {
            if (i is System.DBNull)
                return true;
            else if ((string)i.ToString()=="")
                return true;
            else if ((string)i.ToString().ToLower() == "true")
                return true;
            else if ((string)i.ToString().ToLower() == "false")
                return false;
            else
                return (bool)i;
        }

        public static bool IsNullToFalseForBool(object i)
        {
            if (i is System.DBNull)
                return false;
            else if ((string)i.ToString() == "")
                return false;
            else if ((string)i.ToString().ToLower() == "true")
                return true;
            else if ((string)i.ToString().ToLower() == "false")
                return false;
            else
                return (bool)i;
        }

        public static string ReplaceRegexMetaChars(string pstrText)
        {
            string lstrModifiedText = "";
            lstrModifiedText = pstrText.Replace("\\", "\\\\").Replace(".", "\\.").Replace("(", "\\(").Replace(")", "\\)").Replace("()", "\\(\\)").Replace("{}", "\\{}").Replace("?", "\\?").Replace("*", "\\*").Replace("+", "\\+").Replace("$", "\\$");
            return lstrModifiedText;
        }

        public static int IsNullTo0(object pobjValue)
        {
            if (object.ReferenceEquals(pobjValue, DBNull.Value))
            {
                return 0;
            }
            else
            {
                return Convert.ToInt32(pobjValue);
            }
        }

        /// <summary>
        /// Reverse input string.
        /// </summary>
        public static string Reverse(string value)
        {
            // Convert to char array.
            char[] arr = value.ToCharArray();
            // Use Array.Reverse function.
            Array.Reverse(arr);
            // Construct new string.
            return new string(arr);
        }

        public static int CountCharacter(string value, char ch)
        {
            int cnt = 0;
            foreach (char c in value)
            {
                if (c == ch)
                    cnt += 1;
            }
            return cnt;
        }

        #endregion

        #region "Infragistics"
        public static void ScrollRowToMiddle(UltraGridRow row)
        {
            UltraGrid grid = (UltraGrid)row.Band.Layout.Grid;
            UIElement gridElement = grid.DisplayLayout.UIElement;
            if (gridElement == null)
                return;

            UIElement rowColRegionIntersectionUIElement = gridElement.GetDescendant(typeof(RowColRegionIntersectionUIElement));
            if (rowColRegionIntersectionUIElement == null)
                return;

            // Determine the total number of rows that can fit in the visible
            // area of the grid. We are assuming that the Rows are all the same height.
            int visibleRows = rowColRegionIntersectionUIElement.Rect.Height / row.Height;

            // Find the row that is half the visibleRows prior to the row we want.            
            //
            UltraGridRow newFirstRow = row;
            int rowOffset = visibleRows / 2;
            for (int i = 0; i < rowOffset; i++)
            {
                if (newFirstRow.HasPrevSibling(false, true))
                    newFirstRow = newFirstRow.GetSibling(SiblingRow.Previous, false, true);
            }

            // Set the new FirstRow.
            grid.ActiveRowScrollRegion.FirstRow = newFirstRow;
        }

        public static bool IsRowVisible(CrystalUltraGrid grdData,Infragistics.Win.UltraWinGrid.UltraGridRow row)
        {
            Infragistics.Win.UIElement rowElement =
                grdData.DisplayLayout.UIElement.GetDescendant(
                typeof(Infragistics.Win.UltraWinGrid.RowUIElement), row);

            if (null != rowElement)
            {
                // You can also check if the row is horizontally scrolled out view by
                // checking to see if the row rectangle intersects the grid's rectangle.
                //
                if (!Rectangle.Intersect(grdData.ClientRectangle, rowElement.Rect).IsEmpty)
                    return true;
            }
            return false;
        }

        /// <summary>
        /// To get the cell from the element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static UltraGridCell GetCell(UIElement element)
        {
            if (element == null || element.Parent == null)
            {
                return null;
            }
            if (element.Parent is CellUIElement)
            {
                return ((CellUIElement)element.Parent).Cell;
            }
            else
            {
                return GetCell(element.Parent);
            }
        }

        /// <summary>
        /// To get the column from the element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static UltraGridColumn GetColumn(UIElement element)
        {
            if (element == null || element.Parent == null)
            {
                return null;
            }
            if (element.Parent is HeaderUIElement)
            {
                return ((HeaderUIElement)element.Parent).Header.Column;
            }
            else
            {
                return GetColumn(element.Parent);
            }
        }

        /// <summary>
        /// To get the row from the element
        /// </summary>
        /// <param name="element"></param>
        /// <returns></returns>
        public static UltraGridRow GetRow(UIElement element)
        {
            if (element == null || element.Parent == null)
            {
                return null;
            }
            if (element.Parent is RowUIElement)
            {
                return ((RowUIElement)element.Parent).Row;
            }
            else
            {
                return GetRow(element.Parent);
            }
        }
        #endregion
    }

}
